What is babel-plugin-transform-es2015-typeof-symbol?
The babel-plugin-transform-es2015-typeof-symbol npm package is a plugin for Babel that ensures the behavior of the `typeof` operator is spec-compliant when used with symbols, a new primitive type introduced in ES2015 (ES6). It is part of the Babel's ES2015 preset and is used to transform code so that it can run in environments that do not natively support the new symbol type.
What are babel-plugin-transform-es2015-typeof-symbol's main functionalities?
Transform typeof usage with symbols
This code sample demonstrates how the plugin transforms the `typeof` operator when used with a symbol. The plugin adds a helper function to correctly return 'symbol' when the operand is a symbol.
"use strict";
var _typeof = function (obj) {
return obj && obj.constructor === Symbol ? "symbol" : typeof obj;
};
var sym = Symbol('foo');
console.log(_typeof(sym) === 'symbol'); // true
Other packages similar to babel-plugin-transform-es2015-typeof-symbol
@babel/plugin-transform-typeof-symbol
This is the updated version of the babel-plugin-transform-es2015-typeof-symbol package, which is now scoped under the @babel namespace. It provides the same functionality but is maintained as part of the modern Babel 7 ecosystem.
babel-preset-es2015
This package is a Babel preset that includes babel-plugin-transform-es2015-typeof-symbol among other plugins to transform ES2015 code to be ES5 compliant. It is a more comprehensive solution that includes various transformations for ES2015 features.
babel-plugin-transform-es2015-typeof-symbol
ES6 introduces a new native type called symbols. This transformer wraps all typeof
expressions with a method that replicates native behaviour. (ie. returning "symbol" for symbols)
Example
In
typeof Symbol() === "symbol";
Out
var _typeof = function (obj) {
return obj && obj.constructor === Symbol ? "symbol" : typeof obj;
};
_typeof(Symbol()) === "symbol";
Installation
npm install --save-dev babel-plugin-transform-es2015-typeof-symbol
Usage
Via .babelrc
(Recommended)
.babelrc
{
"plugins": ["transform-es2015-typeof-symbol"]
}
Via CLI
babel --plugins transform-es2015-typeof-symbol script.js
Via Node API
require("babel-core").transform("code", {
plugins: ["transform-es2015-typeof-symbol"]
});